package com.mark.conf.datasourceconf;

import com.alibaba.druid.pool.DruidDataSource;
import com.mark.common.utils.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
/**
 * @Description: 账单能模块数据库的配置
 * @Author: Mark
 * @CreateDate: 2019/01/31 18:32
 * @Version: 2.0
 * @Copyright : 豆浆油条个人非正式工作室
 */
@Configuration
@MapperScan(basePackages = "com.mark.web.bill.mapper", sqlSessionFactoryRef = "myBillSqlSessionFactory")
@Slf4j
public class MyBillDataSourceConf {
    private String className = PropertiesUtil.getDataSourceProperty("bill.database.classname");
    private String url = PropertiesUtil.getDataSourceProperty("bill.database.url");
    private String useName = PropertiesUtil.getDataSourceProperty("bill.database.username");
    private String password = PropertiesUtil.getDataSourceProperty("bill.database.password");
    private String location = PropertiesUtil.getDataSourceProperty("bill.mapper.locations");

    @Bean(name = "myBillDataSource")
    public DataSource myBillSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(className);
        dataSource.setUrl(url);
        dataSource.setUsername(useName);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "myBillTransactionManager")
    public DataSourceTransactionManager myBillDataSourceTransactionManager(){
        return new DataSourceTransactionManager(this.myBillSource());
    }

    @Bean(name = "myBillSqlSessionFactory")
    public SqlSessionFactory myBillSqlSessionFactory(@Qualifier("myBillDataSource") DataSource myBillDataSource) {
        final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //设置数据源
        sqlSessionFactoryBean.setDataSource(myBillDataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            Resource[] resources = resolver.getResources(location);
            //设置mapper.XML文件
            sqlSessionFactoryBean.setMapperLocations(resources);
            return sqlSessionFactoryBean.getObject();
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
